//
//  DDWriteBtnVC.swift
//  swift微博
//
//  Created by whitcast on 16/7/19.
//  Copyright © 2016年 whitcast. All rights reserved.
//

import UIKit
import pop

class DDWriteBtnVC: UIViewController {
    //保存按钮的数组
    var btnArr = [DDCustomBtn]()
    //懒加载数据数组
    private lazy var infosOfBtn: [DDComposeBtnModel] = {
        
        let path = NSBundle.mainBundle().pathForResource("composeBtn.plist", ofType: nil)!
        
        let arr = NSArray(contentsOfFile: path)!
        
        var marr = [DDComposeBtnModel]()
        
        for dict in arr {
            
            let model = DDComposeBtnModel.init(dict: dict as! [String : AnyObject])
            
            marr.append(model)
        }
        
        
        return marr
        
    }()
    //接受背景图片  需要模糊处理
    var backImg: UIImage?{
        didSet{
            backgroundImgView.image = handlePic(backImg!)
        }
    }
    //背景图
    lazy var backgroundImgView: UIImageView = {
        
        let imgView = UIImageView()
        
        imgView.image = self.backImg
        
        return imgView
        
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()
        //接受通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "closeSelf", name: "closeWriteBtnVC", object: nil)
        
    }
    //接受通知,关闭自己
   @objc private func closeSelf() {
        dismissViewControllerAnimated(false, completion: nil)
    
    }
    
    func show() {
        //开始的时候,按顺序执行动画
        for (i,value) in btnArr.enumerate(){
            startAnimation(value, isUp: true, i: i)
        }
        
    }
    //给按钮添加pop动画
    private func startAnimation(btn: UIButton,isUp: Bool,i: Int) {
        
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        let y = isUp ? btn.center.y - 350 : btn.center.y + 350
        
        //到达点
        animation.toValue = NSValue(CGPoint: CGPoint(x: btn.center.x, y: y))
        //初始速度
        animation.springSpeed = 10
        //弹簧效果 [0-20]
        animation.springBounciness = 8
        //开始动画时间  i是btn的tag值
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.05
        //添加动画
        btn.pop_addAnimation(animation, forKey: nil)
        
    }
    
    //创建多个按钮
    private func creatSomebtn() {
        for value in infosOfBtn {
            
            let btn = addChildBtns(value)
            
            //保存进数组
            btnArr.append(btn)
            
            view.addSubview(btn)
            
        }
    }
    //添加并设置按钮
    private func addChildBtns(model: DDComposeBtnModel)->DDCustomBtn{
        
        let btn = DDCustomBtn()
        
        btn.model = model
        //点击事件
        btn.addTarget(self, action: "click:", forControlEvents: .TouchUpInside)
        
        //设置
        return btn
    }
    
    //点击按钮事件
    @objc private func click(sender: DDCustomBtn){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            //循环遍历按钮
            for value in self.btnArr {
                
                value.alpha = 0.2
                
                if value != sender {
                    //缩小不是选中的按钮
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                    
                }else {
                    //放大选中的按钮
                    value.transform = CGAffineTransformMakeScale(3, 3)
                    
                }
            }
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    for value in self.btnArr {
                        value.alpha = 1
//                        //btn改变transform,里面的title和img也会变.但不会变回来,要重写higlighted
//                        value.imageView?.transform = CGAffineTransformIdentity
//                        value.titleLabel?.transform = CGAffineTransformIdentity
                        //这样修改无效
                        value.transform = CGAffineTransformIdentity
                    }
                    
                    }, completion: { (_) -> Void in
                        //跳转控制器
                        //获取目标控制器
                        let vc = NSClassFromString(sender.model!.tagertVC!) as! DDWriteBtnViewController.Type
                        
                        let nav = UINavigationController(rootViewController: vc.init())
                        //跳转
                        self.presentViewController(nav, animated: true, completion: nil)
                        
                })
        }
    }
    
    //设置UI ,约束
    private func setUpUI() {
        
        //背景图片
        view.addSubview(backgroundImgView)
        
        creatSomebtn()
        //约束
        backgroundImgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view.snp_edges).offset(UIEdgeInsetsZero)
        }
        //按钮的宽
        let margin = 10
        //高
        let height: CGFloat = 85.0
        //kuan
        let width: CGFloat = 71
        //间距
        let jianju = (view.frame.size.width - CGFloat(2 * margin) - CGFloat(3 * width))/2.0
        
        for (i,value) in btnArr.enumerate() {
            //行
            let row = i / 3
            //列
            let col = i % 3
            
            
            value.frame.origin.x = CGFloat(margin) + CGFloat(col) * (width + CGFloat(jianju))
            
            value.frame.size = CGSizeMake(width, height)
            
            value.frame.origin.y = CGFloat(margin) + CGFloat(row) * (height + CGFloat(jianju)) + view.frame.size.height
        }
    }
    //处理图片
    private func handlePic(img: UIImage)->UIImage{
        
        let img = img.applyLightEffect()
        
        return img
        
    }
    
    //销毁控制器
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //数组反序
        for (i, value) in btnArr.reverse().enumerate() {
            
            startAnimation(value, isUp: false, i: i)
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //  结束刷新
            self.dismissViewControllerAnimated(false, completion: nil)

        })
        
    }
}
